package com.example.shortvideobackend.service;

import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Service
public class WebRTCSignalingService {

    private final SimpMessagingTemplate messagingTemplate;
    private final Map<String, String> userSessions = new ConcurrentHashMap<>();
    private final Map<String, String> streamSessions = new ConcurrentHashMap<>();

    public WebRTCSignalingService(SimpMessagingTemplate messagingTemplate) {
        this.messagingTemplate = messagingTemplate;
    }

    // 处理用户加入直播
    public void handleJoinStream(String sessionId, String streamKey, String userId) {
        userSessions.put(sessionId, userId);
        streamSessions.put(sessionId, streamKey);
        
        // 通知其他用户有新用户加入
        messagingTemplate.convertAndSend("/topic/stream/" + streamKey + "/join", 
            Map.of("userId", userId, "sessionId", sessionId));
    }

    // 处理用户离开直播
    public void handleLeaveStream(String sessionId) {
        String streamKey = streamSessions.get(sessionId);
        String userId = userSessions.get(sessionId);
        
        if (streamKey != null && userId != null) {
            // 通知其他用户有用户离开
            messagingTemplate.convertAndSend("/topic/stream/" + streamKey + "/leave", 
                Map.of("userId", userId, "sessionId", sessionId));
        }
        
        userSessions.remove(sessionId);
        streamSessions.remove(sessionId);
    }

    // 处理WebRTC offer
    public void handleOffer(String sessionId, Map<String, Object> offer) {
        String streamKey = streamSessions.get(sessionId);
        if (streamKey != null) {
            messagingTemplate.convertAndSend("/topic/stream/" + streamKey + "/offer", offer);
        }
    }

    // 处理WebRTC answer
    public void handleAnswer(String sessionId, Map<String, Object> answer) {
        String streamKey = streamSessions.get(sessionId);
        if (streamKey != null) {
            messagingTemplate.convertAndSend("/topic/stream/" + streamKey + "/answer", answer);
        }
    }

    // 处理ICE candidate
    public void handleIceCandidate(String sessionId, Map<String, Object> candidate) {
        String streamKey = streamSessions.get(sessionId);
        if (streamKey != null) {
            messagingTemplate.convertAndSend("/topic/stream/" + streamKey + "/ice-candidate", candidate);
        }
    }

    // 获取直播间的用户数量
    public int getStreamUserCount(String streamKey) {
        return (int) streamSessions.values().stream()
                .filter(key -> key.equals(streamKey))
                .count();
    }
} 